package com.sky.service.impl;

import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.context.BaseContext;
import com.sky.dto.OrdersDTO;
import com.sky.dto.OrdersSubmitDTO;
import com.sky.dto.OrdersUpStatusDTO;
import com.sky.entity.AddressBook;
import com.sky.entity.OrderDetail;
import com.sky.entity.Orders;
import com.sky.entity.User;
import com.sky.exception.BaseException;
import com.sky.mapper.OrderDetailMapper;
import com.sky.mapper.OrdersMapper;
import com.sky.service.AddressBookService;
import com.sky.service.OrderService;
import com.sky.service.ShoppingCartService;
import com.sky.service.UserService;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.ShoppingCartVO;
import org.aspectj.weaver.ast.Or;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.UUID;

@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    AddressBookService addressBookService;

    @Autowired
    ShoppingCartService shoppingCartService;
    @Autowired
    UserService userService;
    @Autowired
    OrdersMapper ordersMapper;
    @Autowired
    OrderDetailMapper orderDetailsMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public OrderSubmitVO submit(OrdersSubmitDTO dto) {
        // addressBookId查询收货地址
        AddressBook addressBook = addressBookService.selectById(String.valueOf(dto.getAddressBookId()));
        if (addressBook == null) {
            throw new BaseException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }

        // 查询我的购物车，得到菜品或者套餐数据
        List<ShoppingCartVO> list = shoppingCartService.list();
        if (CollectionUtils.isEmpty(list)) {
            throw new BaseException(MessageConstant.SHOPPING_CART_IS_NULL);
        }
        User user = userService.getById(BaseContext.getCurrentId());

        // 生成订单
        // insert orders
        Orders orders = new Orders();
        BeanUtils.copyProperties(dto, orders);
        orders.setNumber(UUID.randomUUID().toString());
        orders.setStatus(Orders.PENDING_PAYMENT);
        orders.setUserId(BaseContext.getCurrentId());
        orders.setUserName(user.getName());
        orders.setOrderTime(LocalDateTime.now());
        orders.setPayStatus(Orders.UN_PAID);
        orders.setPhone(addressBook.getPhone());
        orders.setAddress(addressBook.getProvinceName() + addressBook.getCityName() + addressBook.getDistrictName() + addressBook.getDetail());
        orders.setConsignee(addressBook.getConsignee());
        ordersMapper.insert(orders);


        // insert order_detail
        ArrayList<OrderDetail> orderDetails = new ArrayList<>();
        for (ShoppingCartVO shoppingCartVO : list) {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(shoppingCartVO, orderDetail);
            orderDetail.setId(null);
            orderDetail.setOrderId(orders.getId());
            orderDetails.add(orderDetail);
        }
        orderDetailsMapper.insertBatch(orderDetails);

        // 清空购物车
        shoppingCartService.clean();
        OrderSubmitVO vo = new OrderSubmitVO();
        vo.setId(orders.getId());
        vo.setOrderTime(orders.getOrderTime());
        vo.setOrderAmount(orders.getAmount());
        vo.setOrderNumber(orders.getNumber());
        return vo;
    }

    /**
     * 完成订单
     */
    @Override
    public void orderOK(Long id) {
        Orders orders = ordersMapper.getById(id);

        if (orders == null) {
            throw new BaseException(MessageConstant.ORDER_NOT_FOUND);//订单不存在
        }
        //判断是否是派送中订单
        if (!orders.getStatus().equals(Orders.DELIVERY_IN_PROGRESS)) {
            throw new BaseException(MessageConstant.ORDER_STATUS_ERROR);
        }
        //更新订单状态
        Orders orders1 = new Orders();
        orders1.setId(id);
        orders1.setStatus(Orders.COMPLETED);
        orders1.setDeliveryTime(LocalDateTime.now());
        ordersMapper.updateStatus(orders1);
    }

    /**
     * 取消订单
     */
    @Override
    public void orderNO(OrdersUpStatusDTO dto) {
        Orders orders = ordersMapper.getById(Long.parseLong(String.valueOf(dto.getId())));
        if (orders == null) {
            throw new BaseException(MessageConstant.ORDER_NOT_FOUND);//订单不存在
        }
        Orders orders1 = new Orders();
        orders1.setId(Long.parseLong(String.valueOf(dto.getId())));
        orders1.setStatus(Orders.CANCELLED);
        orders1.setCancelReason(dto.getCancelReason());
        orders1.setCancelTime(LocalDateTime.now());
        ordersMapper.updateStatus(orders1);
    }
}

